<template>
  <div id="root">
<!--    弹窗-->
    <transition>
      <el-dialog :visible.sync="isShowSetting" @close="handleDialogClose">
        <el-form :inline="true" :model="csvSetting" class="demo-form-inline">
          <el-form-item label="原始X">
            <el-select v-model="csvSetting.oriX" placeholder="原始X">
              <el-option v-for="(item,index) in csvHeaders" :key="index" :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="原始Y">
            <el-select v-model="csvSetting.oriY" placeholder="原始Y">
              <el-option v-for="(item,index) in csvHeaders" :key="index" :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <br>
          <el-form-item label="校正X">
            <el-select v-model="csvSetting.desX" placeholder="校正X">
              <el-option v-for="(item,index) in csvHeaders" :key="index" :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="校正Y">
            <el-select v-model="csvSetting.desY" placeholder="校正Y">
              <el-option v-for="(item,index) in csvHeaders" :key="index" :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <br>
          <el-form-item label="道路ID">
            <el-select v-model="csvSetting.roadId" placeholder="道路ID">
              <el-option v-for="(item,index) in csvHeaders" :key="index" :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="点ID">
            <el-select v-model="csvSetting.ID" placeholder="点ID">
              <el-option v-for="(item,index) in csvHeaders" :key="index" :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <br>
          <el-form-item label="图片src">
            <el-select v-model="csvSetting.imgSrc" placeholder="图片src">
              <el-option v-for="(item,index) in csvHeaders" :key="index" :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <br>
          <el-form-item>
            <el-button type="primary" @click="isShowSetting=false">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </transition>
    <el-image-viewer
        ref="imgViewer"
        v-if="isShowImg"
        :url-list="imgList.imgs"
        :z-index="2000"
        :initial-index="imgIndex"
        :on-close="imgClose"
        :on-switch="imgSwitch"
        :on-prev="imgPrev"
        :on-next="imgNext"
    />

    <el-container>
      <el-header>
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <el-button icon="el-icon-s-home" type="primary" @click="$router.push('/')">首页</el-button>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <el-upload
                  class="upload-demo"
                  accept=".json, .geojson"
                  :on-change="roadChange"
                  :file-list="roadList"
                  action=""
                  :auto-upload="false"
                  :show-file-list="false"
                  :limit="1">
                <el-button size="small" type="primary">添加路网</el-button>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <el-upload
                  class="upload-demo"
                  accept=".csv"
                  :on-change="loadCSV"
                  :file-list="roadList"
                  action=""
                  :auto-upload="false"
                  :show-file-list="false">
                <el-button size="small" type="primary">加载CSV文件</el-button>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <el-upload
                  action=""
                  class="upload-demo"
                  ref="uploadDir"
                  :on-change="loadDic"
                  multiple
                  :auto-upload="false"
                  :show-file-list="false">
                <el-button size="small" type="primary">加载文件夹</el-button>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <el-select v-model="activeFile" placeholder="请选择文件">
                <el-option
                    v-for="(item,index) in fileList"
                    :key="index"
                    :label="item.name"
                    :value="index">
                </el-option>
              </el-select>
              <el-button type="success" @click="uploadPoints">校正</el-button>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="grid-content bg-purple">
              <el-dropdown>
                <el-button type="primary">
                  最短路径分析<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-button @click="startShortestPathAnalyze" style="border: none">添加起始点</el-button>
                  <br>
                  <el-button @click="loadShortestPath" style="border: none">生成路径</el-button>
                  <br>
                  <el-button @click="clearShortestPath"  style="border: none">清除路径</el-button>
                </el-dropdown-menu>
              </el-dropdown>

            </div>
          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-aside>
          <div class="aside-top">
            <el-collapse v-model="collapseIndex">
              <el-collapse-item v-for="(item,index) in fileList" :key="index" :title="'🖹 '+item.name"
                                :name="index">
                <div>
                  <el-checkbox v-model="item.oriShow" @change="fileList[index].oriLayer.setVisible(item.oriShow)">原始轨迹
                  </el-checkbox>
                </div>
                <div>
                  <el-checkbox v-model="item.desShow" @change="fileList[index].desLayer.setVisible(item.desShow)">校正轨迹
                  </el-checkbox>
                </div>
                <div>
                  <el-button type="primary" size="mini" @click="exportFile(index)">保存</el-button>
                  <el-button type="danger" size="mini" @click="deleteFile(index)">删除</el-button>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div class="aside-bottom">
            <el-table
                :data="roadInfo"
                :show-header="false"
                style="width: 100%">
              <el-table-column prop="data"></el-table-column>
            </el-table>
          </div>
        </el-aside>
        <el-main>
          <div id="map"></div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import "ol/ol.css";
import "@/../public/css/mapView.css";
import Map from 'ol/Map';
import {Feature, View} from "ol";
import * as olProj from "ol/proj";
import {GeoJSON} from "ol/format";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import axios from "axios";
import * as source from "ol/source";
import {Cluster} from "ol/source";
import TileLayer from "ol/layer/Tile";
import {Modify, Select, Snap} from "ol/interaction";
import {Point} from "ol/geom";
import {Fill, Icon, Stroke, Style} from "ol/style";
import Papa from "papaparse";
import CircleStyle from "ol/style/Circle";
import {click, pointerMove} from "ol/events/condition";
import {executeMatch, getShortestPathByObjectId} from "@/api/road";
import ElImageViewer from './my-image-viewer.vue'
import {getImg} from "@/api/img";

export default {
  name: "OpenMapView",
  components: { ElImageViewer },
  data() {
    return {
      map: null,
      imgList: {
        imgs: [],
        nearFeatures: [],
      },
      isShowImg: false,
      imgIndex: 0,
      isImgLoading: false,
      selectedFileItem: null,
      dicList: [],
      roadList: [],
      roadLayer: null,
      roadSource: null,
      roadSnap: null,
      selectedFeature: null,
      isShowSetting: false,
      csvHeaders: [],
      csvSetting: {oriX: '', oriY: '', desX: '', desY: '', roadId: '', ID: '', imgSrc: ''},
      //csvSetting: {oriX: 0, oriY: 1, desX: 8, desY: 9, roadId: 4, ID: 6, imgSrc: 5},
      fileList: [],
      recentFile: null, //最近打开的文件
      roadInfo: [],
      activeFile: null,
      collapseIndex: [],
      shortestPathPoints: [],
      analyzeShortestPath: false,
      shortestPathLayer: null,
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap();
      //设置上传文件夹
      this.$refs.uploadDir.$children[0].$refs.input.webkitdirectory = true;
      //添加键盘事件
      document.addEventListener('keydown', (e) => {
        //如果ctrl和shift同时按下
        if (e.ctrlKey && e.shiftKey && !this.analyzeShortestPath) {
          //鼠标形状变为手
          this.map.getTargetElement().style.cursor = 'pointer';
        }
      })
      //添加键盘弹起事件
      document.addEventListener('keyup', (e) => {
        if (!this.analyzeShortestPath && (e.ctrlKey || e.shiftKey)) {
          //鼠标形状变为手
          this.map.getTargetElement().style.cursor = 'default';
        }
      })

      //弹窗提示
      let that = this
      window.onbeforeunload = function (e) {
        if(that.$route.fullPath ==="/openMap"){
          e = e || window.event;
          if (e) {
            e.returnValue = '关闭提示';
          }
          return '关闭提示';
        } else {
          window.onbeforeunload = null
        }
      };

  })
  },
  methods: {
    initMap() {
      let self = this;
      this.map = new Map({
        target: 'map',
        layers: [],
        view: new View({
          center: olProj.fromLonLat([114.37, 30.50]),
          zoom: 13,
        })
      });
      //设置wms图层
      let wmsSource = new source.TileWMS({
        url: 'geoapi/'+this.$store.state.workspace+'/wms',
        params: {
          'FORMAT': 'image/png',
          'VERSION': '1.1.1',
          tiled: true,
          "LAYERS": this.$store.state.workspace+':'+this.$store.state.layer,
          "exceptions": 'application/vnd.ogc.se_inimage',
        },
        serverType: 'geoserver',
        crossOrigin: 'anonymous',
      });
      let wmsLayer = new TileLayer({
        source: wmsSource,
      });
      this.map.addLayer(wmsLayer);


      //设置路网图层
      this.roadSource = new VectorSource();
      this.roadLayer = new VectorLayer({
        source: this.roadSource
      });
      this.map.addLayer(this.roadLayer);

      //设置选中路网的样式
      let select = new Select({
        layers: [this.roadLayer],
        style: function (feature) {
          return new Style({
            stroke: new Stroke({
              color: '#f00',
              width: 2
            }),
            fill: new Fill({
              color: 'rgba(255,0,0,0.1)'
            })
          });
        }
      });

      this.map.addInteraction(select);

      select.on("select", function (e) {
        let feature = e.selected[0];
        if (feature) {
          self.roadInfo = [{data: "OBJECTID: " + feature.get("OBJECTID")}]
        }

      })
      this.map.on('moveend', () => {
        if (this.map.getView().getZoom() > 16.5) {
          this.updateRoadsLayer();
        } else {
          this.roadSource.clear();
        }
      })


      //给路网图层设置选择事件
      let pmSelect = new Select({
        layers: [this.roadLayer],
        condition: function (e) {
          return e.type === "singleclick" && e.originalEvent.ctrlKey && e.originalEvent.shiftKey;
        },
      });
      pmSelect.on("select", function (e) {
        let feature = e.selected[0];
        //获取feature上离鼠标最近的点
        let point = feature.getGeometry().getClosestPoint(e.mapBrowserEvent.coordinate);
        //将点的坐标转换为经纬度
        point = olProj.transform(point, 'EPSG:3857', 'EPSG:4326');
        self.panoramicMap(point[0], point[1]);
      })

      this.map.addInteraction(pmSelect);


      //设置最短路径图层
      this.map.on('click', (e) => {
        if (this.analyzeShortestPath){
          //设置最短路径起始点
          // 获取点击位置的feature
          let feature = this.map.forEachFeatureAtPixel(e.pixel, function (feature) {
            return feature.get("features")[0];
          });
          //如果有feature，且是点要素, 且this.shortestPathPoints.length == 0 则设置起始点
          if (feature && feature.getGeometry().getType() === "Point" && this.shortestPathPoints.length === 0) {
            this.shortestPathPoints.push(feature);
            //在feature位置添加一个圆形
            let point = feature.getGeometry();
            let iconFeature = new Feature({
              geometry: new Point(point.getCoordinates()),
              name: 'Null Island',
              population: 4000,
              rainfall: 500
            });
            let iconStyle = new Style({
              image: new CircleStyle({
                radius: 7,
                fill: new Fill({
                  color: '#35b03b'
                }),
              })
            });
            iconFeature.setStyle(iconStyle);
            let source = new VectorSource({
              features: [iconFeature]
            });
            this.shortestPathLayer = new VectorLayer({
              source: source
            });
            this.map.addLayer(this.shortestPathLayer);
          }
          else if (feature && feature.getGeometry().getType() === "Point" && this.shortestPathPoints.length === 1) {
            this.shortestPathPoints.push(feature);
            //在feature位置添加点
            let point = feature.getGeometry();
            let iconFeature = new Feature({
              geometry: new Point(point.getCoordinates()),
              name: 'Null Island',
              population: 4000,
              rainfall: 500
            });
            let iconStyle = new Style({
              image: new CircleStyle({
                radius: 7,
                fill: new Fill({
                  color: '#d536da'
                }),
              })
            });
            iconFeature.setStyle(iconStyle);
            this.shortestPathLayer.getSource().addFeature(iconFeature);
          }
          if (this.shortestPathPoints.length === 2) {
            this.analyzeShortestPath = false;
            //设置鼠标形状
            this.map.getTargetElement().style.cursor = "default";
          }
        }
      })

    },
    roadChange(file) {
    },
    //加载单个文件
    loadCSV(file) {
      //读取CSV文件
      let reader = new FileReader();
      reader.readAsText(file.raw);
      reader.onload = () => {
        let csv = reader.result;
        //加载CSV文件并把第一行作为表头
        let data = Papa.parse(csv, {header: true}).data;
        this.csvHeaders = Object.keys(data[0]);
        let fileItem = {
          ID: 0,
          isLoaded: true,
          file: null,
          name: file.name,
          data: data,
          oriShow: true,
          desShow: true,
          oriLayer: null,
          desLayer: null,
          modify: null,
          select: null,
        }
        this.recentFile = fileItem;
        if (this.csvSetting.oriX === '' || this.csvSetting.oriY === '' ||
            this.csvSetting.desX === '' || this.csvSetting.desY === '' ||
            this.csvSetting.roadId === '' || this.csvSetting.ID === '') {
          this.isShowSetting = true;
        } else {
          this.addFile(fileItem);
        }
      }
    },
    loadDic(file){
        let fileItem = {
          ID: 0,
          isLoaded: false,
          file: file,
          name: file.name,
          data: null,
          oriShow: true,
          desShow: true,
          oriLayer: null,
          desLayer: null,
          modify: null,
          select: null,
          clickSelect: null,
        }
        this.fileList.push(fileItem)
    },
    addFile(fileItem) {
      //添加原始轨迹图层
      let oriFeatures = [];
      fileItem.data.forEach(item => {
        let feature = new Feature({
          geometry: new Point(olProj.fromLonLat([item[this.csvSetting.oriX], item[this.csvSetting.oriY]])),
          pointId: item[this.csvSetting.ID],
          roadId: item[this.csvSetting.roadId],
          imgSrc: item[this.csvSetting.imgSrc],
          fileItem: fileItem
        });
        oriFeatures.push(feature);
      })
      for(let i = 0;i<oriFeatures.length;i++){
        let feature = oriFeatures[i];
        let preFeature = i>0?oriFeatures[i-1]:null;
        let nextFeature = i<oriFeatures.length-1?oriFeatures[i+1]:null;
        feature.set("nearFeature",[preFeature,nextFeature]);
      }


      let oriClusterSource = new Cluster({
        distance: 7,
        source: new VectorSource({
          features: oriFeatures
        })
      });


      fileItem.oriLayer = new VectorLayer({
        source: oriClusterSource,
        style: new Style({
          image: new CircleStyle({
            radius: 5,
            fill: new Fill({
              color: '#d73c83'
            })
          })
        })
      });
      this.map.addLayer(fileItem.oriLayer);
      //添加目标轨迹图层
      this.setDesLayer(fileItem);
      this.map.addLayer(fileItem.desLayer);
      //判断this.fileList中是否已经存在该文件
      let index = this.fileList.findIndex(item => item.name === fileItem.name);
      if (index === -1) {
        this.fileList.push(fileItem);
      } else {
        this.fileList[index] = fileItem;
      }
      //将地图缩放到合适的位置
      let extent = fileItem.oriLayer.getSource().getSource().getExtent();
      this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
    },
    deleteFile(index) {
      this.map.removeLayer(this.fileList[index].oriLayer);
      this.map.removeLayer(this.fileList[index].desLayer);
      this.map.removeInteraction(this.fileList[index].modify);
      this.map.removeInteraction(this.fileList[index].select);
      this.map.removeInteraction(this.fileList[index].clickSelect);
      this.fileList.splice(index, 1);
    },
    saveChanges(index) {
      //将desLayer的数据修改到原始数据中
      let desFeatures = this.fileList[index].desLayer.getSource().getSource().getFeatures();
      desFeatures.forEach(feature => {
        let pointId = feature.get("pointId");
        let roadId = feature.get("roadId");
        this.fileList[index].data.forEach(item => {
          if (item[this.csvSetting.ID] === pointId) {
            item[this.csvSetting.roadId] = roadId;
            item[this.csvSetting.desX] = olProj.toLonLat(feature.getGeometry().getCoordinates())[0];
            item[this.csvSetting.desY] = olProj.toLonLat(feature.getGeometry().getCoordinates())[1];
          }
        })
      })
      let csvData = [];
      //添加数据
      this.fileList[index].data.forEach(item => {
        let csvItem = {};
        for (let key in item) {
          csvItem[key] = item[key];
        }
        //判断是否为null，如果为null则不添加
        if (csvItem[this.csvSetting.roadId] !== undefined){
          csvData.push(csvItem);
        }
      })
      return csvData;
    },
    exportFile(index) {
      let csvData = this.saveChanges(index);
      //导出csv文件
      let csv = Papa.unparse(csvData);
      let blob = new Blob(["\ufeff" + csv], {type: 'text/csv;charset=utf-8;'});
      let url = URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.href = url;
      link.download = this.fileList[index].name;
      link.click();
    },
    updateRoadsLayer() {
      axios.get("geoapi/"+this.$store.state.workspace+"/ows", {
        params: {
          service: "WFS",
          version: "1.0.0",
          request: "GetFeature",
          typeName: this.$store.state.workspace+":"+this.$store.state.layer,
          outputFormat: "application/json",
          bbox: this.map.getView().calculateExtent().join(',') + ',EPSG:3857',
        }
      }).then(res => {
        let features = new GeoJSON().readFeatures(res.data);
        //对features做坐标转换
        features.forEach(feature => {
          feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
        })
        this.roadSource.clear();
        this.roadSource.addFeatures(features);
        this.map.removeInteraction(this.roadSnap);
        this.roadSnap = new Snap({
          source: this.roadSource,
          pixelTolerance: 10
        });
        this.map.addInteraction(this.roadSnap);
      })
    },
    handleDialogClose() {
      this.addFile(this.recentFile);
    },
    uploadPoints() {
      let csvData = this.saveChanges(this.activeFile);
      let setting = this.csvSetting;
      executeMatch(csvData, setting.roadId, setting.desX, setting.desY, setting.oriX, setting.oriY).then(res => {
        //更新data
        this.fileList[this.activeFile].data = res.data;
        //移除原始图层
        this.map.removeLayer(this.fileList[this.activeFile].desLayer);
        //设置desLayer
        this.setDesLayer(this.fileList[this.activeFile]);
        //添加desLayer
        this.map.addLayer(this.fileList[this.activeFile].desLayer);

      }).catch(err => {
        console.log(err);
      })

    },
    setDesLayer(fileItem) {
      if (fileItem.modify && fileItem.select) {
        this.map.removeInteraction(fileItem.modify);
        this.map.removeInteraction(fileItem.select);
      }
      //添加校正轨迹图层
      let desFeatures = [];
      fileItem.data.forEach(item => {
        let feature = new Feature({
          geometry: new Point(olProj.fromLonLat([item[this.csvSetting.desX], item[this.csvSetting.desY]])),
          pointId: item[this.csvSetting.ID],
          roadId: item[this.csvSetting.roadId],
          imgSrc: item[this.csvSetting.imgSrc],
        });
        desFeatures.push(feature);
      })
      for(let i = 0;i<desFeatures.length;i++){
        let feature = desFeatures[i];
        let preFeature = i>0?desFeatures[i-1]:null;
        let nextFeature = i<desFeatures.length-1?desFeatures[i+1]:null;
        feature.set("nearFeature",[preFeature,nextFeature]);
      }
      let desClusterSource = new Cluster({
        distance: 7,
        source: new VectorSource({
          features: desFeatures
        })
      });
      let modify = new Modify({
        source: desClusterSource,
        condition: function (event) {
          //设置alt+左键为修改
          return event.originalEvent.button === 0 && event.originalEvent.altKey;
        },
      });

      //修改结束后，判断点在哪条线上
      modify.on("modifyend", (e) => {
        //修改坐标
        const eps = 0.0000001;
        let pointFeatures = e.features.getArray()[0].get("features");
        pointFeatures[0].getGeometry().setCoordinates(e.mapBrowserEvent.coordinate);
        let point = pointFeatures[0].getGeometry();
        //遍历lineSource中的feature，判断点在那条线上
        this.roadSource.forEachFeature((feature) => {
          let line = feature.getGeometry();
          let closestPoint = line.getClosestPoint(point.getCoordinates());
          if (Math.abs(closestPoint[0] - point.getCoordinates()[0]) < eps && Math.abs(closestPoint[1] - point.getCoordinates()[1]) < eps) {
            pointFeatures[0].set("roadId", feature.get("OBJECTID"));
          }
        })
      })
      fileItem.modify = modify;
      this.map.addInteraction(modify);
      fileItem.desLayer = new VectorLayer({
        source: desClusterSource,
        style: new Style({
          image: new CircleStyle({
            radius: 5,
            fill: new Fill({
              color: '#ffcc33'
            })
          })
        })
      });
      //为点添加鼠标移入事件
      let select = new Select({
        condition: pointerMove,
        layers: [fileItem.oriLayer, fileItem.desLayer],
      });
      select.on("select", (e) => {
        let feature = e.selected[0];
        //获取feature的原始feature
        if (feature) {
          if (feature.get("features")) {
            feature = feature.get("features")[0];
          }
          this.roadInfo = [
            {data: "ID: " + feature.get("pointId")},
            {data: "roadId: " + feature.get("roadId")},
          ];
        }
      })
      fileItem.select = select;

      //为点添加鼠标点击事件
      let clickSelect = new Select({
        condition: function (event) {
          return event.type === "singleclick" && event.originalEvent.button === 0 && event.originalEvent.ctrlKey;
        },
        layers: [fileItem.oriLayer, fileItem.desLayer],
      });
      clickSelect.on("select", (e) => {
        let feature = e.selected[0]?.get("features")[0];
        if(!feature){
          return;
        }
        let imgSrc = feature.get("imgSrc");
        let nearFeature = feature.get("nearFeature");
        //把imgSrc中的\替换为/
        imgSrc = imgSrc.replace(/\\/g, "/");
        getImg(imgSrc).then(res=>{
          this.imgList = {
            imgs: [res.data],
            nearFeatures: [nearFeature]
          }
          this.isShowImg = true;
          this.imgIndex = 0;
        }).catch(err=>{
          console.log(err)
        })
      })
      fileItem.clickSelect = clickSelect;
      this.map.addInteraction(clickSelect);
      this.map.addInteraction(select);
    },
    startShortestPathAnalyze(){
      //鼠标形状变成十字
      console.log(this.shortestPathPoints)
      this.map.getTargetElement().style.cursor = "crosshair";
      this.analyzeShortestPath = true;
      this.shortestPathPoints = [];
    },
    clearShortestPath(){
      this.shortestPathPoints = [];
      this.map.getTargetElement().style.cursor = "default";
      this.analyzeShortestPath = false;
      this.map.removeLayer(this.shortestPathLayer);
      this.shortestPathLayer = null;
    },
    loadShortestPath(){
      let startId = this.shortestPathPoints[0].get("features")[0].get("roadId");
      let endId = this.shortestPathPoints[1].get("features")[0].get("roadId");
      getShortestPathByObjectId(startId,endId).then(res=>{
        let path = res.data;
        let pathFeature = new Feature({
          geometry: new GeoJSON().readGeometry(path),
        })
        pathFeature.setStyle(new Style({
          stroke: new Stroke({
            color: 'rgb(53,104,176)',
            width: 4
          })
        }))
        pathFeature.getGeometry().transform('EPSG:4326', 'EPSG:3857');
        this.shortestPathLayer.getSource().addFeature(pathFeature);
      }).catch(err=>{
        console.log(err)
      })
    },
    imgClose(){
      this.isShowImg = false;
      this.imgList = {
        urlList: [],
        idList: [],
      };
    },
    imgSwitch(index,type){
      this.imgIndex = index;
    },
    imgPrev(){
      //如果上一个请求还没完成，不允许点击
      if (this.isImgLoading) {
        this.$notify({
          title: '提示',
          message: '请耐心等待上一个请求完成',
          type: 'warning'
        });
        return;
      }

      //如果是第一张，点击上一张
      if (this.imgIndex === 0) {
        let prevFeature = this.imgList.nearFeatures[0][0];
        //如果index为-1，说明没有上一个点
        if (!prevFeature) {
          this.$notify({
            title: '提示',
            message: '已经是第一张了',
            type: 'warning'
          });
        }
        else {
          let src = prevFeature.get("imgSrc");
          //把src中的\替换为/
          src = src.replace(/\\/g, "/");
          this.isImgLoading = true;
          getImg(src).then(res => {
            this.imgList.imgs.unshift(res.data);
            this.imgList.nearFeatures.unshift(prevFeature.get("nearFeature"));
            this.imgIndex = 0;
            this.isImgLoading = false;
          }).catch(err => {
            console.log(err)
          })
        }
      }
    },
    imgNext(){
      //如果上一个请求还没完成，不允许点击
      if (this.isImgLoading) {
        this.$notify({
          title: '提示',
          message: '请耐心等待上一个请求完成',
          type: 'warning'
        });
        return;
      }

      //如果是最后一张，点击下一张
      if (this.imgIndex === this.imgList.imgs.length - 1) {
        let nextFeature = this.imgList.nearFeatures[this.imgList.nearFeatures.length - 1][1];
        //如果index为-1，说明没有上一个点
        if (!nextFeature) {
          this.$notify({
            title: '提示',
            message: '已经是最后一张了',
            type: 'warning'
          });
        }
        else {
          let src = nextFeature.get("imgSrc");
          //把src中的\替换为/
          src = src.replace(/\\/g, "/");
          this.isImgLoading = true;
          getImg(src).then(res => {
            this.imgList.imgs.push(res.data);
            this.imgList.nearFeatures.push(nextFeature.get("nearFeature"));
            this.imgIndex = this.imgList.imgs.length - 1;
            this.isImgLoading = false;
          }).catch(err => {
            console.log(err)
          })
        }
      }
    },
    panoramicMap(longitude, latitude){
      axios.get("/transform/geoconv/v1/?coords="+longitude+","+latitude+"&from=1&to=6&ak=DQzYGQQb4EQdwTAgm35iQNflt4IkuH22").then(res => {
        let lon = parseFloat(res.data.result[0].x);
        let lat = parseFloat(res.data.result[0].y);

        axios.get("https://mapsv0.bdimg.com/?qt=qsdata&x="+lon+"&y="+lat).then(res => {
          if(res.data.result.error == 0){
            this.$notify({
              title: res.data.content.RoadName,
              message: res.data.content.id,
              type: 'success'
            });
            setTimeout(() => {
              window.open("https://map.baidu.com/#panoid="+res.data.content.id+"&panotype=street")
            }, 1000)
          }
          else if (res.data.result.error == 404){
            this.$notify({
              title: "404NotFound",
              type: 'warning'
            });
          }
          else {
            this.$notify({
              title: "查询失败",
              type: 'warning'
            });
          }

        }).catch(err => {
          this.$notify({
            title: "查询失败",
            type: 'warning'
          });
          console.log(err)
        })
      }).catch(err => {
        console.log(err)
      })
    },
  },
  watch: {
    collapseIndex(newVal, oldVal) {
      //如果newVal的长度比oldVal的长度大1，说明是展开了一个新的面板
      if (newVal.length - oldVal.length === 1) {
        //获取新展开的面板的index
        let index = newVal[newVal.length - 1];
        let fileItem = this.fileList[index];
        if(!fileItem.isLoaded){
          //如果该文件没有加载过，加载该文件
          let file = fileItem.file;
          let reader = new FileReader();
          reader.readAsText(file.raw);
          reader.onload = () => {
            let csv = reader.result;
            let data = Papa.parse(csv).data;
            this.csvHeaders = data[0];
            let fileItem = {
              ID: 0,
              isLoaded: true,
              file: null,
              name: file.name,
              data: data.slice(1),
              oriShow: true,
              desShow: true,
              oriLayer: null,
              desLayer: null,
              modify: null,
              select: null,
              clickSelect: null,
            }
            this.recentFile = fileItem;
            if (this.csvSetting.oriX === '' || this.csvSetting.oriY === '' ||
                this.csvSetting.desX === '' || this.csvSetting.desY === '' ||
                this.csvSetting.roadId === '' || this.csvSetting.ID === '') {
              this.isShowSetting = true;
            } else {
              this.addFile(fileItem);
            }
          }
        }


      }
    },
  },
}
</script>

<style scoped>
/deep/ .el-form-item__label {
  color: #020202 !important;
  font-size: medium;
}

/deep/ .el-collapse-item__header {
  font-size: 18px;
}

/deep/ .el-table .cell {
  line-height: 12px;
}
</style>
